import { SourceView } from '../view'
import Editor from '../editor'
import isHotkey from 'is-hotkey'

export class KeyboardEvent {
  editor
  container
  view
  isComposing: boolean = false
  // keydownEvent
  constructor(editor: Editor, container: HTMLElement, view: SourceView) {
    this.editor = editor
    this.container = container
    this.view = view
  }
  beforeInputHandler_(e: InputEvent) {
    const inputType = e.inputType
    console.log(inputType, 'inputType')
    if (inputType === 'insertCompositionText' || inputType === 'deleteCompositionText') {
      return
    }
    e.preventDefault()
    let text = null
    switch (inputType) {
      case 'insertText':
        text = e.data
        if (text) {
          this.editor.insertTextAtCursor(text)
        }
        break
      case 'insertFromPaste':
        const data = e.dataTransfer
        text = data && data.getData('text/plain')
        if (text) {
          this.editor.insertTextAtCursor(text);
        }
      case 'insertParagraph':
        console.log('insertParagraph')
        this.editor.insertTextAtCursor('\n')
        break
      case 'deleteContentBackward':
        this.editor.deleteTextCursor()
        break
    }
  }
  keydownInputHandler_ (e: globalThis.KeyboardEvent) {
    if (isHotkey('mod+z', e)) {
        this.editor.undo()
    }
  }
  compositionStartHandler_ () {
    this.isComposing = true // 正在中文输入
  }
  compositionEndHandler_ (e: CompositionEvent) {
    this.isComposing = false // 中文输入结束
    const text = e.data;
    if (text) {
      this.editor.insertTextAtCursor(text);
    }
  }
  selectionChangeHandler_(selection: { anchor: number, focus: number }) {
    if (this.isComposing) {
      return
    }
    if (selection) {
      this.editor.setSelection(selection.anchor, selection.focus)
      console.log(selection.anchor, selection.focus, '坐标')
    }
  }
  addListeners() {
    this.container.addEventListener('beforeinput', this.beforeInputHandler_.bind(this))
    this.container.addEventListener('keydown', this.keydownInputHandler_.bind(this))
    this.container.addEventListener('compositionend', this.compositionEndHandler_.bind(this))
    this.container.addEventListener('compositionstart', this.compositionStartHandler_.bind(this))
    // this.container.addEventListener('selectionchange')
    window.document.addEventListener('selectionchange', this.view.updateDomSelection.bind(this.view))
    this.view.on('selection-change', this.selectionChangeHandler_.bind(this))
    // new KeydownEvent(this.editor, this.container, this.view)
    // this.keydownEvent.addListeners()
  }
}

export default KeyboardEvent